# /usr/bin/python
# coding: utf-8
import pymysql
import csv

sql = ""
boolen = False


def buildSqlStr(DB_TABLE):
    # 读取文件 修改数据库字段
    alterTable = "alter table %s " % DB_TABLE
    sql = " change {}  {} {} ,"
    with open("./csv.csv") as f:
        reader = csv.reader(f)
        next(reader)  # 跳过头部
        for i, row in enumerate(reader):
            length = len(row)
            # 遍历文件
            if length > 3:
                # 如果一条记录长度大于3则希望修改
                if length == 4:
                    # 参数齐全
                    boolen = True
                    alterTable += sql.format(row[0], row[2], row[3])
                else:
                    # 缺少参数
                    print("--第%s行，缺少参数，请检查！" % (i))
        alterTable = alterTable[:-1]
        sql = alterTable
        exePrint()
        f.close()


def exeSql(dbConfig, DB_TABLE):
    buildSqlStr(DB_TABLE)
    if boolen:
        db = pymysql.connect(**dbConfig)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
        except Exception as e:
            print("发生错误", repr(e))
        finally:
            db.close()
    else:
        exePrint()


def exePrint():
    if boolen:
        print("组合sql为:")
        print(sql)
        print("-"*20)
    else:
        print("未检测到csv文件修改!")
